"use client"

import type React from "react"

import { useState } from "react"
import Image from "next/image"
import { Camera } from "lucide-react"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import type { UserProfile } from "@/types/user"
import { updateUserProfile } from "@/lib/api-client"

// Define preset images
const AVATAR_PRESETS = [
  "/img/avatar/1.jpg",
  "/img/avatar/2.jpg",
  "/img/avatar/3.jpg",
  "/img/avatar/4.jpg",
]

const COVER_PRESETS = ["/img/cover/1.jpg", "/img/cover/2.jpg", "/img/cover/3.jpg", "/img/cover/4.jpg"]

interface EditProfileDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  profile: UserProfile
  onProfileUpdate: (profile: Partial<UserProfile>) => void
}

export function EditProfileDialog({ open, onOpenChange, profile, onProfileUpdate }: EditProfileDialogProps) {
  const [name, setName] = useState(profile.username)
  const [bio, setBio] = useState(profile.bio || "")
  const [avatarFile, setAvatarFile] = useState<File | null>(null)
  const [coverFile, setCoverFile] = useState<File | null>(null)
  const [avatarPreview, setAvatarPreview] = useState<string | null>(null)
  const [coverPreview, setCoverPreview] = useState<string | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [showAvatarPresets, setShowAvatarPresets] = useState(false)
  const [showCoverPresets, setShowCoverPresets] = useState(false)

  const handleAvatarChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0]
      setAvatarFile(file)
      setAvatarPreview(URL.createObjectURL(file))
    }
  }

  const handleCoverChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0]
      setCoverFile(file)
      setCoverPreview(URL.createObjectURL(file))
    }
  }

  const selectAvatarPreset = (preset: string) => {
    setAvatarPreview(preset)
    setAvatarFile(null)
    setShowAvatarPresets(false)
  }

  const selectCoverPreset = (preset: string) => {
    setCoverPreview(preset)
    setCoverFile(null)
    setShowCoverPresets(false)
  }

  const toggleAvatarPresets = () => {
    setShowAvatarPresets(!showAvatarPresets)
  }

  const toggleCoverPresets = () => {
    setShowCoverPresets(!showCoverPresets)
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setIsSubmitting(true)

    try {
      const updateData: {
        name?: string
        bio?: string
        avatar?: File | string
        cover?: File | string
      } = {}

      if (name !== profile.username) updateData.name = name
      if (bio !== profile.bio) updateData.bio = bio
      if (avatarFile) updateData.avatar = avatarFile
      else if (avatarPreview) updateData.avatar = avatarPreview
      if (coverFile) updateData.cover = coverFile
      else if (coverPreview) updateData.cover = coverPreview

      const response = await updateUserProfile(updateData)

      // Update the profile in the parent component
      onProfileUpdate({
        username: name,
        bio,
        avatar: avatarPreview || profile.avatar,
        cover: coverPreview || profile.cover,
      })

      onOpenChange(false)
    } catch (error) {
      console.error("Error updating profile:", error)
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
      <Dialog open={open} onOpenChange={onOpenChange}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>编辑个人资料</DialogTitle>
          </DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-6">
            <div className="space-y-4">
              <div>
                <Label htmlFor="avatar-upload" className="block text-center">
                  头像
                </Label>
                <div className="relative mx-auto mt-2 h-24 w-24 overflow-hidden rounded-full border">
                  <Image
                      src={avatarPreview || profile.avatar || "/placeholder.svg?height=96&width=96"}
                      alt="Avatar"
                      fill
                      className="object-cover"
                  />
                  <div className="absolute inset-0 flex cursor-pointer items-center justify-center bg-black/50 opacity-0 transition-opacity hover:opacity-100">
                    <label htmlFor="avatar-upload" className="flex h-full w-full items-center justify-center">
                      <Camera className="h-6 w-6 text-white" />
                    </label>
                    <input
                        id="avatar-upload"
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={handleAvatarChange}
                    />
                  </div>
                </div>
                <div className="mt-2 flex justify-center gap-2">
                  <Button type="button" size="sm" variant="outline" onClick={toggleAvatarPresets}>
                    预设
                  </Button>
                  <label htmlFor="avatar-upload">
                    <Button type="button" size="sm" variant="outline" asChild>
                      <span>上传</span>
                    </Button>
                  </label>
                </div>
                {showAvatarPresets && (
                    <div className="mt-2 grid grid-cols-4 gap-2">
                      {AVATAR_PRESETS.map((preset, index) => (
                          <div
                              key={index}
                              className="relative h-16 w-16 cursor-pointer overflow-hidden rounded-full border"
                              onClick={() => selectAvatarPreset(preset)}
                          >
                            <Image
                                src={preset || "/placeholder.svg"}
                                alt={`Preset ${index + 1}`}
                                fill
                                className="object-cover"
                            />
                          </div>
                      ))}
                    </div>
                )}
              </div>

              <div>
                <Label htmlFor="cover-upload" className="block text-center">
                  封面图
                </Label>
                <div className="relative mt-2 h-32 w-full overflow-hidden rounded-md border">
                  <Image
                      src={coverPreview || profile.cover || "/placeholder.svg?height=128&width=400"}
                      alt="Cover"
                      fill
                      className="object-cover"
                  />
                  <div className="absolute inset-0 flex cursor-pointer items-center justify-center bg-black/50 opacity-0 transition-opacity hover:opacity-100">
                    <label htmlFor="cover-upload" className="flex h-full w-full items-center justify-center">
                      <Camera className="h-8 w-8 text-white" />
                    </label>
                    <input
                        id="cover-upload"
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={handleCoverChange}
                    />
                  </div>
                </div>
                <div className="mt-2 flex justify-center gap-2">
                  <Button type="button" size="sm" variant="outline" onClick={toggleCoverPresets}>
                    预设
                  </Button>
                  <label htmlFor="cover-upload">
                    <Button type="button" size="sm" variant="outline" asChild>
                      <span>上传</span>
                    </Button>
                  </label>
                </div>
                {showCoverPresets && (
                    <div className="mt-2 grid grid-cols-2 gap-2">
                      {COVER_PRESETS.map((preset, index) => (
                          <div
                              key={index}
                              className="relative h-20 cursor-pointer overflow-hidden rounded-md border"
                              onClick={() => selectCoverPreset(preset)}
                          >
                            <Image
                                src={preset || "/placeholder.svg"}
                                alt={`Preset ${index + 1}`}
                                fill
                                className="object-cover"
                            />
                          </div>
                      ))}
                    </div>
                )}
              </div>

              <div>
                <Label htmlFor="name">昵称</Label>
                <Input id="name" value={name} onChange={(e) => setName(e.target.value)} className="mt-1" />
              </div>

              <div>
                <Label htmlFor="bio">个性签名</Label>
                <Textarea
                    id="bio"
                    value={bio}
                    onChange={(e) => setBio(e.target.value)}
                    className="mt-1 h-20"
                    placeholder="这个人很懒，什么都没有写~"
                />
              </div>
            </div>

            <div className="flex justify-end gap-2">
              <Button type="button" variant="outline" onClick={() => onOpenChange(false)} disabled={isSubmitting}>
                取消
              </Button>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting ? "保存中..." : "保存"}
              </Button>
            </div>
          </form>
        </DialogContent>
      </Dialog>
  )
}

